package mammuthus.client

import java.util
import java.util.Collections

import com.webdm.common.tools.CatchUtil

import scala.collection.JavaConversions._

/**
  * Created by fbj on 15-2-3 下午4:52.
  */
object ConfUtils {


  /**
    * 合成配置文件,主要处理引用
    * @param conf
    * @param context
    * @return
    */
   def merge(conf: String, context: java.util.Map[String, String]): String = {

     var result = conf
     val list = new util.ArrayList[String](1000)

     if(result != null && context != null){
       conf.split("\r\n|\n").foreach(line => {

          if(line.contains("%{")){

            var finalLine = line
            CatchUtil.getValues(line, "%\\{(.*?)\\}", 1).foreach(l => {


              val name = "%{" + l + "}"
              if(context.containsKey(l)){

                var conf = context.get(l)
                val prefix = line.substring(0, line.indexOf(name))

                //处理配置对齐
                if(!prefix.isEmpty && prefix.matches("^\\s+$")){
                    conf = conf.split("\r\n|\n").map(prefix + _).mkString("\n").trim
                }


                finalLine = finalLine.replace(name, conf)
                //println(conf)
               // println(finalLine)
              }

            })
            list.add(finalLine)
          }else{
            list.add(line)

          }

       })

       result = list.mkString("\n")


     }
     return result
   }


   /**
    * 找出配置文件中的所有引用
    * @param conf
    * @return
    */
   def analyze(conf: String):java.util.Set[String] = {

     if(conf != null && !conf.isEmpty){

       val list =  CatchUtil.getValues(conf, "\\%\\{(.*?)\\}", 1)

       if(list != null) return new util.HashSet[String](list)

     }

     return new util.HashSet[String]()



   }




 }
